package org.wsocket.config;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.wsocket.Exception.WSocketException;


public class WSocketConfigCacheFile {

	private Logger log = Logger.getLogger(this.getClass());
	/**
	 * The property file
	 */
	private File propertyFile;
	/**
	 * The property object
	 */
	private Properties prop = new Properties();
	/**
	 * Flag to indicate if the properties are loaded
	 */
	private boolean propLoaded = false;

	/**
	 * The constructor. The paramneters of service type and name is used to
	 * identifiy which set of configuration to load
	 * 
	 * @param protpertyFileName
	 * @throws WSocketException
	 */
	public WSocketConfigCacheFile(File protpertyFile) throws WSocketException {
		this.propertyFile = protpertyFile;
		loadProperties();
	}

	/**
	 * Returns the value of the configuration attribute
	 * 
	 * @param name
	 *            The name of the configuration attribute
	 * @return The value of the attribute
	 * @throws WSocketException
	 */
	public String getValue(String name) throws WSocketException {
		if (!propLoaded) {
			loadProperties();
		}
		return prop.getProperty(name, "");
	}

	// public void refresh() throws WSocketException {
	// //reload config
	// WSocketLoader.init();
	// }

	/**
	 * Refresh the congif cache by re-reading it from the file
	 * 
	 * @throws WSocketException
	 */
	private void loadProperties() throws WSocketException {

		try {
			// load all the properties .
			prop.clear();
			prop.load(new FileInputStream(propertyFile));
			propLoaded = true;
		} catch (Exception e) {
			log.error("Error opening " + propertyFile);
			throw new WSocketException(e);
		}
	}
}
